using System;
using System.Threading;
using System.Windows.Forms;
using FlickrShots.Framework;
using Timer=System.Windows.Forms.Timer;

namespace FlickrShots.GUI.controls
{
    public partial class WallpaperSettingsControl : UserControl
    {
        private Wallpapr wallpaper;
        private Timer timer = new Timer();
        public WallpaperSettingsControl()
        {
            InitializeComponent();
            //timer.Tick += new EventHandler(timer_Tick);
            //timer.Start();
            
//            Initialize();
//            selectedPhotos.SelectionChangeCommitted += new EventHandler(SelectionChangeCommitted);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            int refreshRate = (int)Preferences.Instance.AutoRefreshRate.TotalMilliseconds;
            if (refreshRate > 0)
            {
                timer.Interval = refreshRate;
                PreviewNextWallpaper(sender, e);
                ChangeWallpaper(sender, e);
            }
            else
            {
                timer.Interval = 1000;
            }
        }

//        private void Initialize()
//        {
//            photoTypes.SelectedIndex = 0;
//
//            selectedPhotos.Items.Add(new EveryonesPhotoStream());
//            //selectedPhotos.Items.Add(new UsersPhotoStream(Authenticatr.CurrentUser));
//            selectedPhotos.Items.Add(new FriendsPhotoStream());
//            selectedPhotos.SelectedIndex = 0;
//        }

        public event EventHandler PhotoSelectionChanged;

//        private void SelectionChangeCommitted(object sender, EventArgs e)
//        {
//            if (PhotoSelectionChanged != null)
//            {
//                PhotoSelectionChanged(this, e);
//            }
//        }

        private void ChangeWallpaper(object sender, EventArgs e)
        {
            if (wallpaper == null)
            {
                GetNextWallpaper();
            }
            wallpaper.SetAsDesktopWallpaper();
        }

        private void PreviewNextWallpaper(object sender, EventArgs e)
        {
            GetNextWallpaper();
            pictureBox1.Image = wallpaper.PreviewImage;
            pictureBox1.Text = wallpaper.Title;
            propertyGrid1.SelectedObject = wallpaper;
        }

        private Retrievr retrievr = new Retrievr();
        private Wallpapr GetNextWallpaper()
        {
            retrievr.PhotoStream = new EveryonesPhotoStream();
            if (txtTags.TextLength > 0)
            {
                retrievr.PhotoStream = new TagPhotoStream(txtTags.Lines);
            }
            else if (txtUserName.TextLength > 0)
            {
                retrievr.PhotoStream = new UsersPhotoStream(txtUserName.Text);
            }
            return wallpaper = retrievr.GetNextWallpaper();
        }
    }
}
